package br.perfiman.dao.impl;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import br.perfiman.dao.PortfolioDAOService;
import br.perfiman.model.Asset;
import br.perfiman.model.Portfolio;
import br.perfiman.model.Trade;

/**
 *
 * @author Wagner Costa
 * @since 08/03/2008
 * @version 1.0
 *
 */
@Stateless
public class PortfolioDAOServiceBean extends AbstractDAOServiceBean<Portfolio> implements PortfolioDAOService {

	@PersistenceContext(unitName="perfiman")
    public EntityManager em;

	@Override
	public EntityManager getEntityManager() {
		return em;
	}

	@SuppressWarnings("unchecked")
	public Portfolio retrieveByAsset(Asset asset) throws Exception {
		List<Portfolio> list =  em.createQuery("FROM Portfolio p where p.asset.symbol like :asset")
			.setParameter("asset", asset.getSymbol())
			.getResultList();
		if(list == null || list.size() == 0)
			return null;
		return list.get(0);
	}

	public void removeAll() throws Exception {
		em.createQuery("DELETE FROM Portfolio p").executeUpdate();
	}

	@SuppressWarnings("unchecked")
	public List<Trade> getTrades() {
		return em.createQuery("FROM Trade t where t.operationType = :operationType")
		.setParameter("operationType", Trade.OPERATION_TYPE_COMMON)
		.getResultList();
	}
}
